const adminModel = require('../../model/admin/admin')
const md5 = require('md5')
const checkIsLogin = require('../../../config/check').checkIsLogin

// 检测是否登录
exports.getLogin = async ctx => {
    await checkIsLogin(ctx)
    await ctx.render('login', {
        session: ctx.session,
    })
}
// 请求登录
exports.login = async ctx => {
    let { userName, password } = ctx.request.body
    //验证用户名是否有效
    await adminModel.findAdminUserByName(userName)
        .then(res => {
            if (res.length>0 && userName === res[0]['name'] && md5(password) === res[0]['password']) {
                ctx.session = {
                    user: res[0]['name'],
                    id: res[0]['id']
                }
                ctx.body = {
                    access: ['super_admin', 'admin'],
                    token: res[0]['name'],
                    nmae:res[0]['name'],
                    user_id:res[0]['id'],
                    avatar: 'https://file.iviewui.com/dist/a0e88e83800f138b94d2414621bd9704.png',
                    code: 0,
                    msg: '登录成功'
                }
            }
            else {
                ctx.body = {
                    code: -1,
                    msg: '用户名或密码错误'
                }
            }
        })
        .catch(err => {
            ctx.body = {
                msg: err,
                code: -2
            }
        })
}
//退出登录
exports.logOut = async ctx=>{
    let  userName = ctx.request.body
    await adminModel.findAdminUserByName(userName).then(
        res=>{
            ctx.body = {
                code: 0,
                msg: '退出成功'
            }
        }
    ).catch(res=>{
        ctx.body = {
            msg: err,
            code: -2
        }
    })
}

